package com.baor.service.impl;
import com.baor.dao.DeliverDao;
import com.baor.dao.Equipment_instructionsDao;
import com.baor.domain.Deliver;
import com.baor.domain.Equipment;
import com.baor.service.DeliverService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DeliverServiceImpl implements DeliverService {

    @Autowired
    private DeliverDao deliverDao;

    @Autowired
    private Equipment_instructionsDao equipmentDao;

    @Override
    public R add(Map<String, Object> params) {
        try {
            // 1. 参数验证
            if (params.get("title") == null || ((String) params.get("title")).trim().isEmpty()) {
                return R.er("标题不能为空");
            }

            // 2. 处理应用设备逻辑
            String applyType = (String) params.get("applyType");

            List<Integer> deviceIds = null;
            if (params.get("deviceIds") != null) {
                deviceIds = ((List<?>) params.get("deviceIds"))
                        .stream()
                        .map(id -> Integer.parseInt(id.toString()))
                        .collect(Collectors.toList());
            }

            // 获取目标设备ID列表
            List<Integer> targetEquipmentIds = getTargetEquipmentIds(applyType, deviceIds);

            if (targetEquipmentIds.isEmpty()) {
                return R.er("未选择任何有效设备");
            }

            // 3. 保存每个设备到数据库（每条记录对应一个设备）
            int successCount = 0;

            for (Integer equipmentId : targetEquipmentIds) {
                Deliver deviceDeliver = new Deliver();
                deviceDeliver.setTitle(params.get("title").toString());
                deviceDeliver.setImage(params.get("image").toString());
                deviceDeliver.setEquipmentId(equipmentId); // 设置单个设备ID

                // 处理显示状态
                Object displayObj = params.get("display");
                if (displayObj != null) {
                    deviceDeliver.setDisplay(Integer.parseInt(displayObj.toString()));
                } else {
                    deviceDeliver.setDisplay(1); // 默认显示
                }

                deviceDeliver.setIsDeleted(0);

                int result = deliverDao.insert(deviceDeliver);
                if (result > 0) {
                    successCount++;
                }
            }

            if (successCount > 0) {
                return R.ok("添加成功，共添加 " + successCount + " 条设备记录");
            } else {
                return R.er("添加失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.er("系统错误: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public R update(Map<String, Object> params) {
        try {
            // 1. 参数验证
            if (params.get("id") == null) {
                return R.er("ID不能为空");
            }

            // 获取要修改的记录ID
            Integer id = Integer.parseInt(params.get("id").toString());

            // 2. 检查记录是否存在
            Deliver existingDeliver = deliverDao.selectById(id);
            if (existingDeliver == null || existingDeliver.getIsDeleted() == 1) {
                return R.er("记录不存在或已被删除");
            }

            // 3. 获取标题，用于查找同一投递规则的所有记录
            String title = existingDeliver.getTitle();

            // 4. 处理应用设备逻辑
            String applyType = (String) params.get("applyType");
            List<Integer> deviceIds = null;

            if (params.get("deviceIds") != null) {
                deviceIds = ((List<?>) params.get("deviceIds"))
                        .stream()
                        .map(item -> Integer.parseInt(item.toString()))
                        .collect(Collectors.toList());
            }

            // 获取目标设备ID列表
            List<Integer> targetEquipmentIds = getTargetEquipmentIds(applyType, deviceIds);

            if (targetEquipmentIds.isEmpty()) {
                return R.er("未选择任何有效设备");
            }

            // 5. 删除同一投递规则的所有旧记录
            List<Deliver> allDelivers = deliverDao.selectList(null);
            List<Deliver> sameTitleDelivers = allDelivers.stream()
                    .filter(deliver -> deliver.getIsDeleted() == 0 &&
                            title.equals(deliver.getTitle()))
                    .collect(Collectors.toList());

            for (Deliver deliver : sameTitleDelivers) {
                Deliver deleteDeliver = new Deliver();
                deleteDeliver.setId(deliver.getId());
                deleteDeliver.setIsDeleted(1);
                deliverDao.updateById(deleteDeliver);
            }

            // 6. 创建新的记录
            int successCount = 0;

            for (Integer equipmentId : targetEquipmentIds) {
                Deliver newDeliver = new Deliver();
                newDeliver.setTitle((String) params.get("title"));
                newDeliver.setImage((String) params.get("image"));
                newDeliver.setEquipmentId(equipmentId);

                // 处理显示状态
                Object displayObj = params.get("display");
                if (displayObj != null) {
                    newDeliver.setDisplay(Integer.parseInt(displayObj.toString()));
                } else {
                    newDeliver.setDisplay(1); // 默认显示
                }

                newDeliver.setIsDeleted(0);

                int result = deliverDao.insert(newDeliver);
                if (result > 0) {
                    successCount++;
                }
            }

            if (successCount > 0) {
                return R.ok("修改成功，共更新 " + successCount + " 条设备记录");
            } else {
                return R.er("修改失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.er("系统错误: " + e.getMessage());
        }
    }
    @Override
    public R getList(Map<String, Object> params) {
        try {
            // 1. 查询所有未删除的记录
            MPJLambdaWrapper<Deliver> wrapper = new MPJLambdaWrapper<>(Deliver.class)
                    .selectAll(Deliver.class)
                    .eq(Deliver::getIsDeleted, 0)
                    .orderByDesc(Deliver::getId);

            List<Deliver> allDelivers = deliverDao.selectList(wrapper);

            // 2. 按 title 分组，并聚合设备 ID
            Map<String, Map<String, Object>> groupedByTitle = new LinkedHashMap<>();

            for (Deliver deliver : allDelivers) {
                String title = deliver.getTitle();

                if (!groupedByTitle.containsKey(title)) {
                    // 第一次遇到这个标题，创建分组
                    Map<String, Object> group = new HashMap<>();
                    group.put("id", deliver.getId()); // 使用第一条记录的ID作为代表
                    group.put("title", title);
                    group.put("image", deliver.getImage());
                    group.put("display", deliver.getDisplay());
                    group.put("createAt", deliver.getCreateAt());
                    group.put("updateAt", deliver.getUpdateAt());
                    group.put("equipmentIds", new ArrayList<Integer>());
                    groupedByTitle.put(title, group);
                }

                // 将设备ID添加到对应分组的设备ID列表中
                @SuppressWarnings("unchecked")
                List<Integer> equipmentIds = (List<Integer>) groupedByTitle.get(title).get("equipmentIds");
                if (deliver.getEquipmentId() != null) {
                    equipmentIds.add(deliver.getEquipmentId());
                }
            }

            // 3. 转换为列表
            List<Map<String, Object>> resultList = new ArrayList<>(groupedByTitle.values());

            // 4. 分页处理
            int pageIndex = (Integer) params.get("pageIndex");
            int pageSize = (Integer) params.get("pageSize");
            int total = resultList.size();

            // 计算分页
            int fromIndex = (pageIndex - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, total);

            if (fromIndex > total) {
                fromIndex = total;
            }

            List<Map<String, Object>> pagedList = resultList.subList(fromIndex, toIndex);

            // 5. 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("total", total);
            result.put("list", pagedList);

            return R.ok(result);

        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询失败: " + e.getMessage());
        }
    }

    @Override
    public R getById(Integer id) {
        try {
            // 1. 根据ID查询记录
            MPJLambdaWrapper<Deliver> wrapper = new MPJLambdaWrapper<>(Deliver.class)
                    .selectAll(Deliver.class)
                    .eq(Deliver::getIsDeleted, 0)
                    .eq(Deliver::getId, id);
            Deliver deliver = deliverDao.selectOne(wrapper);

            if (deliver == null) {
                return R.er("记录不存在");
            }

            // 2. 根据标题查询所有相同标题的记录
            String title = deliver.getTitle();
            MPJLambdaWrapper<Deliver> titleWrapper = new MPJLambdaWrapper<>(Deliver.class)
                    .selectAll(Deliver.class)
                    .eq(Deliver::getIsDeleted, 0)
                    .eq(Deliver::getTitle, title);
            List<Deliver> sameTitleDelivers = deliverDao.selectList(titleWrapper);

            // 3. 组装返回数据，按照 title 分组并聚合设备 ID
            Map<String, Object> result = new HashMap<>();
            result.put("id", deliver.getId());
            result.put("title", title);
            result.put("image", deliver.getImage());
            result.put("display", deliver.getDisplay());
            result.put("createAt", deliver.getCreateAt());
            result.put("updateAt", deliver.getUpdateAt());

            // 4. 收集设备 ID 列表
            List<Integer> equipmentIds = sameTitleDelivers.stream()
                    .map(Deliver::getEquipmentId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            result.put("equipmentIds", equipmentIds);

            // 5. 返回结果
            return R.ok(result);

        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询失败: " + e.getMessage());
        }
    }
    /**
     * 根据应用类型获取目标设备ID列表
     */
    private List<Integer> getTargetEquipmentIds(String applyType, List<Integer> deviceIds) {
        List<Integer> equipmentIds;

        try {
            if ("0".equals(applyType)) {
                // 全部设备
                List<Equipment> allEquipments = equipmentDao.selectAllEquipment();
                equipmentIds = allEquipments.stream()
                        .map(Equipment::getId)
                        .collect(Collectors.toList());
                System.out.println("全部设备数量: " + equipmentIds.size());

            } else if ("1".equals(applyType)) {
                // 应用部分设备 - 直接使用传入的设备ID
                if (deviceIds != null && !deviceIds.isEmpty()) {
                    // 验证设备ID是否存在
                    List<Integer> validIds = validateEquipmentIds(deviceIds);
                    equipmentIds = new ArrayList<>(validIds);
                    System.out.println("应用部分设备数量: " + equipmentIds.size());
                } else {
                    throw new IllegalArgumentException("应用部分设备模式需要传入设备ID");
                }

            } else if ("2".equals(applyType)) {
                // 屏蔽部分设备 - 从所有设备中排除传入的设备ID
                List<Equipment> allEquipments = equipmentDao.selectAllEquipment();
                // 创建排除设备ID集合
                Set<Integer> excludeIds = deviceIds != null ? new HashSet<>(deviceIds) : new HashSet<>();
                System.out.println("排除设备数量: " + excludeIds.size());
                equipmentIds = allEquipments.stream()
                        .map(Equipment::getId)
                        .filter(id -> !excludeIds.contains(id))
                        .collect(Collectors.toList());
                System.out.println("屏蔽后设备数量: " + equipmentIds.size());

            } else {
                throw new IllegalArgumentException("不支持的应用类型: " + applyType);
            }
        } catch (Exception e) {
            System.out.println("设备选择错误: " + e.getMessage());
            throw e;
        }

        return equipmentIds;
    }

    /**
     * 验证设备ID是否存在
     */
    private List<Integer> validateEquipmentIds(List<Integer> equipmentIds) {
        List<Integer> validIds = new ArrayList<>();
        for (Integer id : equipmentIds) {
            try {
                Equipment equipment = equipmentDao.selectById(id);
                if (equipment != null && equipment.getIsDeleted() == 0) {
                    validIds.add(id);
                } else {
                    System.out.println("警告：设备ID " + id + " 不存在或已被删除");
                }
            } catch (Exception e) {
                System.out.println("验证设备ID " + id + " 时出错: " + e.getMessage());
            }
        }
        return validIds;
    }
}